package com.tensquare.user.controller;

import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 登陆功能
     */
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public Result login(@RequestBody Admin admin){
        Admin adminLogin = adminService.login(admin);
        if (null == adminLogin){
            return new Result(false,StatusCode.LOGINERROR,"登陆失败");
        }
        //如果说有值
        //似的前后端可以通过的操作，采用jwt来实现
        String token = jwtUtil.createJWT(adminLogin.getId(),adminLogin.getLoginname(),"admin");
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("token",token);
        map.put("role","admin");
        return new Result(true,StatusCode.OK,"登录成功",map);
    }


    //查询全部
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll(){
        return new Result(true, StatusCode.OK,"查询成功",adminService.findAll());
    }



    /**
     * 根据ID查询管理员
     */
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public Result findById(@PathVariable String id){
        return new Result(true,StatusCode.OK,"查询成功",adminService.findById(id));
    }



    //增加
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody  Admin admin){
      adminService.add(admin);
      return new Result(true,StatusCode.OK,"增加完成");
    }
    //删除
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public Result deleteById(@PathVariable String  id) {
        adminService.deleteById(id);
        return new Result(true,StatusCode.OK,"删除成功");
    }
    //改
    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public Result update(@RequestBody Admin admin,@PathVariable String id){
        admin.setId(id);
        adminService.update(admin);
        return new Result(true,StatusCode.OK,"修改成功");
    }
}
